package core;

import Utils.tempWorkTree;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

//删除文件
public class JitRemove {

    public static void remove(String filepath) throws IOException {

        tempWorkTree.updateWorkTree();

        File file = new File(filepath);
        if(!file.exists()){
            System.out.println("该文件不存在");
            return;
        }
        if (file.isFile())
            removeFile(file,filepath);
        else if (file.isDirectory())
            removeDir(file,filepath);
    }

    public static void removeFile(File file,String filepath) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        List<String> allLines = Files.readAllLines(Paths.get(tempWorkTree.indexLoc));
        for (String allLine : allLines) {
            if(!allLine.contains(filepath)){
                stringBuilder.append(allLine+"\n");
            }
        }
        FileOutputStream fileOutputStream = new FileOutputStream(tempWorkTree.indexLoc,false);
        fileOutputStream.write(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
        fileOutputStream.close();
    }

    public static void removeDir(File file,String filepath) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        List<String> allLines = Files.readAllLines(Paths.get(tempWorkTree.indexLoc));
        for (String allLine : allLines) {
            if(!allLine.contains(filepath)){
                stringBuilder.append(allLine+"\n");
            }
        }
        FileOutputStream fileOutputStream = new FileOutputStream(tempWorkTree.indexLoc,false);
        fileOutputStream.write(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
        fileOutputStream.close();
    }
}
